package org.jeecg.modules.iot.config.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class DeviceDecoder extends ByteToMessageDecoder {
    private final String PACKET_FLAG = "AA55";
    // 头+长度+协议类型+设备地址+设备类型+协议版本+数据+校验
    private final int BASE_LENGTH = 2+1+1+1+1+1+1+1;
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("decode bytes length -> "+in.readableBytes());
        if(in.readableBytes()>=BASE_LENGTH) {
            if(in.readableBytes()>2048) {
                in.skipBytes(in.readableBytes());
            }
            int index;
            String header;
            while(true){
                index = in.readerIndex();
                in.markReaderIndex();
                byte[] dst = new byte[2];
                in.readBytes(dst, 0, 2);
                header = ConvertCode.bytes2HexString(dst);
                if(PACKET_FLAG.equals(header))
                    break;
                in.resetReaderIndex();
                in.readByte();
                if(in.readableBytes()<BASE_LENGTH)
                    return;
            }
            log.info("-----找到包头------");
            byte length= in.readByte();
            byte protocolType = in.readByte();
            byte deviceSn = in.readByte();
            byte deviceType = in.readByte();
            byte version = in.readByte();
            log.info("in.readableBytes()--"+in.readableBytes()+"---"+length);
            // 加上校验和字节
            if(in.readableBytes()<length+1) {
                // 如果数据域长度不够，回滚之前的操作到header，等数据长度够了再继续，断帧情况
                log.info("断包-----------");
                in.readerIndex(index);
                return;
            }
            byte[] payload = new byte[length];
            in.readBytes(payload);
            byte checksum = in.readByte();
            DeviceProtocol protocol = new DeviceProtocol(header,version,
            protocolType,deviceSn,length, deviceType, payload,checksum);
            out.add(protocol);
        }
    }
}
